﻿<%@ WebHandler Language="C#" Class="GetDeviceInfo" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;


public class GetDeviceInfo : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/json";
        //获取前台传过来的方法名
        string methodName = context.Request["method"];
        //判断方法名是否正确
        if (methodName == "savetoken"){//判断是否为保存token的方法
            //获取前台ajax传过来的token数据
            string token = context.Request["token"];
            //获得当前系统时间（字符串格式）
            DateTime systemTime = DateTime.Now;
            DataSet a = YunCutDBHelper.Query("select top 1 createtime,id from token order by id desc");
            DateTime time = Convert.ToDateTime("2010-01-01 00:00:00");
            int tid = 0;
            foreach (DataRow dr in a.Tables[0].Rows){
                time= (DateTime)dr[0];
                tid= (Int32)dr[1];
            }
            //数据库时间和系统时间比较
            System.TimeSpan st = systemTime.Subtract(time);
            //获得小时差
            int timehours = (Int32)st.Hours;
            //获得天数差
            int timedays = (Int32)st.Days;
            // st.Days.ToString()：获取"天"
            // +st.Hours.ToString()获取："小时"
            // +st.Minutes.ToString()获取："分钟"
            // +st.Seconds.ToString()获取："秒"; 
            //如果时间差大于两个小时以上重新添加token
            if (timehours>2 || timedays>0){
                if (tid!=0){
                    //修改token状态
                    string sql = "update token set state = '已失效' where id = "+tid+"";
                    YunCutDBHelper.ExecuteSql(sql);
                }
                //插入数据库  
                string strSql = "insert into token(token,state,createtime)values('" + token + "','未失效','" + systemTime + "')";
                YunCutDBHelper.ExecuteSql(strSql);
            }
        }else if (methodName == "querytoken"){//判断是否为查询token和sysid的方法
            //查询从数据库获取到最后token指令
            DataSet a = YunCutDBHelper.Query("select top 1 token from token order by id desc");
            //查询获取到所有的sysid并进行循环
            DataSet aa = YunCutDBHelper.Query("select sysid from device ");
            //遍历循环DataSet结果集
            string sysidList = "";
            foreach (DataRow dr in a.Tables[0].Rows){
                sysidList = sysidList + "{ \"token\":\"" + dr[0].ToString() + "\",\"sysids\":[";
            }
            foreach (DataRow dr in aa.Tables[0].Rows){
                sysidList = sysidList + "{ \"sysid\":\"" + dr[0].ToString() + "\"},";
            }
            sysidList = sysidList.Substring(0, sysidList.Length - 1);//去掉最后的一个逗号
            sysidList = sysidList + "]}";
            context.Response.Write(sysidList.ToString());
        }
        else if (methodName == "savedeviceinfo")
        {//判断是否为保存当前设备信息数据的方法
         //获取前台ajax传过来的设备信息数据
            string deviceinfo = context.Request["deviceinfo"];
            //将前台传过来的json格式装换为String类型
            JObject jo = (JObject)JsonConvert.DeserializeObject(deviceinfo);
            string msg = "";
            if (deviceinfo.IndexOf("\"msg\":") > -1){
                msg = jo["msg"].ToString();
            }
            string code = "";
            if (deviceinfo.IndexOf("\"msg\":") > -1){
                code = jo["code"].ToString();
            }
            string date = "";
            if (deviceinfo.IndexOf("\"date\":") > -1){
                date = jo["date"].ToString();
            }
            string systemtime = "";
            if (deviceinfo.IndexOf("\"systemtime\":") > -1){
                systemtime = jo["systemtime"].ToString();
            }
            string setinterval = "";
            if (deviceinfo.IndexOf("\"setinterval\":") > -1){
                setinterval = jo["setinterval"].ToString();
            }
            string gjstlastminutes = "";
            if (deviceinfo.IndexOf("\"gjstlastminutes\":") > -1){
                gjstlastminutes = jo["gjstlastminutes"].ToString();
            }
            string endtime = "";
            if (deviceinfo.IndexOf("\"endtime\":") > -1){
                endtime = jo["endtime"].ToString();
            }
            string sysid = "";
            if (deviceinfo.IndexOf("\"sysid\":") > -1){
                sysid = jo["sysid"].ToString();
            }
            string name = "";
            if (deviceinfo.IndexOf("\"name\":") > -1){
                name = jo["name"].ToString();
            }
            //解析的设备信息
            string duration_name = "";
            if (deviceinfo.IndexOf("\"duration_name\":") > -1){
                duration_name = jo["duration_name"].ToString();
            }
            string duration = "";
            if (deviceinfo.IndexOf("\"duration\":") > -1){
                duration = jo["duration"].ToString();
            }
            string warning_name = "";
            if (deviceinfo.IndexOf("\"warning_name\":") > -1){
                warning_name = jo["warning_name"].ToString();
            }
            string warning = "";
            if (deviceinfo.IndexOf("\"warning\":") > -1){
                warning = jo["warning"].ToString();
            }
            string companyid = "";
            if (deviceinfo.IndexOf("\"companyid\":") > -1){
                companyid = jo["companyid"].ToString();
            }
            string companyname = "";
            if (deviceinfo.IndexOf("\"companyname\":") > -1){
                companyname = jo["companyname"].ToString();
            }
            string deptid = "";
            if (deviceinfo.IndexOf("\"deptid\":") > -1)
            {
                deptid = jo["deptid"].ToString();
            }
            string deptname = "";
            if (deviceinfo.IndexOf("\"deptname\":") > -1){
                deptname = jo["deptname"].ToString();
            }
            string device_type = "";
            if (deviceinfo.IndexOf("\"device_type\":") > -1){
                device_type = jo["device_type"].ToString();
            }
            string cmodel = "";
            if (deviceinfo.IndexOf("\"cmodel\":") > -1){
                cmodel = jo["cmodel"].ToString();
            }
            string cname = "";
            if (deviceinfo.IndexOf("\"cname\":") > -1){
                cname = jo["cname"].ToString();
            }
            string dmodel = "";
            if (deviceinfo.IndexOf("\"dmodel\":") > -1){
                dmodel = jo["dmodel"].ToString();
            }
            string dname = "";
            if (deviceinfo.IndexOf("\"dname\":") > -1){
                dname = jo["dname"].ToString();
            }
            string quitesysid = "";
            if (deviceinfo.IndexOf("\"quitesysid\":") > -1){
                quitesysid = jo["quitesysid"].ToString();
            }
            string worknumcol = "";
            if (deviceinfo.IndexOf("\"worknumcol\":") > -1){
                worknumcol = jo["worknumcol"].ToString();
            }
            string repstatu = "";
            if (deviceinfo.IndexOf("\"repstatu\":") > -1){
                repstatu = jo["repstatu"].ToString();
            }
            string repstatuname = "";
            if (deviceinfo.IndexOf("\"repstatuname\":") > -1){
                repstatuname = jo["repstatuname"].ToString();
            }
            string workstatucol = "";
            if (deviceinfo.IndexOf("\"workstatucol\":") > -1){
                workstatucol = jo["workstatucol"].ToString();
            }
            string workalarmcol = "";
            if (deviceinfo.IndexOf("\"workalarmcol\":") > -1){
                workalarmcol = jo["workalarmcol"].ToString();
            }
            string params_list = "";
            if (deviceinfo.IndexOf("\"params_list\":") > -1){
                params_list = jo["params_list"].ToString();
            }
            string strSql = "insert into device_info(request_state,statecode,time,systemtime,setinterval,gjstlastminutes," +
                "endtime,sysid,name,duration_name,duration,warning_name,warning,companyid,companyname," +
                "deptid,deptname,device_type,cmodel,cname,dmodel,dname,quitesysid,worknumcol,repstatu," +
                "repstatuname,workstatucol,workalarmcol,params_list)" +
                 "values('" + msg + "','" + code + "','" + date + "','" + systemtime + "','" + setinterval + "','" + gjstlastminutes + "','" + endtime + "','" + sysid + "','" + name + "'" +
                       ",'" + duration_name + "','" + duration + "','" + warning_name + "','" + warning + "','" + companyid + "','" + companyname + "','" + deptid + "','" + deptname + "','" + device_type + "'" +
                       ",'" + cmodel + "','" + cname + "','" + dmodel + "','" + dname + "','" + quitesysid + "','" + worknumcol + "','" + repstatu + "','" + repstatuname + "','" + workstatucol + "'" +
                       ",'" + workalarmcol + "','" + params_list + "')";
            YunCutDBHelper.ExecuteSql(strSql);

        }
        else if (methodName == "savehistorydeviceinfo")
        {//判断是否为保存历史数据方法名
         //获取前台ajax传过来的设备信息数据
            string deviceinfo = context.Request["deviceinfo"];
            //将前台传过来的json格式装换为String类型
            JObject jo = (JObject)JsonConvert.DeserializeObject(deviceinfo);
            string sysid = jo["sysid"].ToString();
            //将历史设备信息的时间保存到数据库
            string sqlstr = "insert into history_device_info_time (code,msg,stime,etime,sysid)values('" + jo["code"].ToString() + "','" + jo["msg"].ToString() + "','" + jo["stime"].ToString() + "','" + jo["etime"].ToString() + "','" + sysid + "')";
            YunCutDBHelper.ExecuteSql(sqlstr);
            //查询主表id
            int tid = (int)YunCutDBHelper.GetSingle("select top 1 id from history_device_info_time order by id desc");
            string _key = "";
            JToken _value = null;
            foreach (JToken child in jo.Children()){
                var property1 = child as JProperty;
                _key = property1.Name.ToString();
                _value = property1.Value;
                string sql = "";
                string values = "|";
                string values_ = "|";
                foreach (JToken _child in _value){
                    var property2 = child as JProperty;
                    values += property2.Name.ToString() + "|";
                    foreach (JToken child1 in values){
                        var property3 = _child as JProperty;
                        values_ += property3.Name.ToString() + "|";
                    }
                }
                if (values_.Contains("|cvalue|")){
                    sql = "insert into history_device_info_parameter (name,type,value,cvalue,tid)values('" + _key + "','" + _value["type"] + "','" + _value["value"] + "','" + _value["cvalue"] + "'," + tid + ")";
                    YunCutDBHelper.ExecuteSql(sql);
                }else if (values_.Contains("|type|") && values_.Contains("|value|")){
                    sql = "insert into history_device_info_parameter (name,type,value,tid)values('" + _key + "','" + _value["type"] + "','" + _value["value"] + "'," + tid + ")";
                    YunCutDBHelper.ExecuteSql(sql);
                }
            }
            JObject job = (JObject)JsonConvert.DeserializeObject(jo["runstatu"].ToString());
            JObject job1 = (JObject)JsonConvert.DeserializeObject(jo["alarmstatu"].ToString());
            string runstatu = "runstatu";
            string alarmstatu = "alarmstatu";
            string sql1 = "insert into history_device_info_statu (name,ass,tss,fss,name1,ass1,tss1,fss1,tid)" +
            "values('" + runstatu + "','" + job["as"].ToString() + "','" + job["ts"].ToString() + "','" + job["fs"].ToString() + "','" + alarmstatu + "','" + job1["as"].ToString() + "','" + job1["ts"].ToString() + "','" + job1["fs"].ToString() + "'," + tid + ")";
            YunCutDBHelper.ExecuteSql(sql1);
        }else if (methodName == "querydevice"){//判断是否为查询当前设备信息的方法
            //查询从数据库查询当前设备信息
            DataSet ds = YunCutDBHelper.Query("select top 19 d.name,s.ass,s.tss,d.time from history_device_info_statu s INNER JOIN history_device_info_time t ON t.id = s.tid INNER JOIN device_info d ON d.sysid = t.sysid order by d.id desc");
            //遍历循环DataSet结果集
            string sysIdList = "[";
            foreach (DataRow dr in ds.Tables[0].Rows){
                //查询历史设备信息状态时间，计算稼动率
                decimal ass = Convert.ToInt32(dr[1]);
                decimal tss = Convert.ToInt32(dr[2]);
                Decimal jdl = Math.Round((tss / ass) * 100, 1);
                sysIdList = sysIdList + "{ \"name\":\"" + dr[0].ToString() + "\","
                + " \"jdl\":\"" + jdl + "%" + "\","
                + " \"time\":\"" + dr[3].ToString() + "\"},";
            }
            sysIdList = sysIdList.Substring(0, sysIdList.Length - 1);//去掉最后的一个逗号
            sysIdList = sysIdList + "]";
            context.Response.Write(sysIdList.ToString());
        }else if (methodName == "querytime"){//查询设备时间信息
            //查询从数据库查询当前设备历史一小时信息
            DataSet ds = YunCutDBHelper.Query("select top 19 d.name,s.tss1,s.tss,s.fss,s.ass from history_device_info_statu s INNER JOIN history_device_info_time t ON t.id = s.tid INNER JOIN device_info d ON d.sysid = t.sysid order by d.id desc");
            foreach (DataRow dr in ds.Tables[0].Rows){
                //一小时内运行时长
                decimal tss = Convert.ToInt32(dr[2]);
                //一小时内待机时长
                decimal fss = Convert.ToInt32(dr[3]);
                //一小时总时长
                decimal ass = Convert.ToInt32(dr[4]);
                //稼动率
                Decimal jdl = Math.Round((tss / ass) * 100, 1);
                string sql = "insert into history_device_info (name,jdl,tss,fss)values('" + dr[0].ToString() + "'," + jdl + ",'" + tss + "','" + fss + "')";
                YunCutDBHelper.ExecuteSql(sql);
            }
            DataSet ds1 = YunCutDBHelper.Query("select a.name,a.jdl,a.tss,a.fss  from history_device_info a inner join (select top 19 id from history_device_info order by id desc) as b on b.id=a.id order by a.jdl desc");
            //遍历循环DataSet结果集
            string sysIdList = "[";
            foreach (DataRow dr in ds1.Tables[0].Rows){
                sysIdList = sysIdList + "{ \"name\":\"" + dr[0].ToString() + "\","
                + " \"warning\":\"" + dr[1].ToString() + "%" + "\","
                + " \"tss\":\"" + dr[2].ToString() + "\","
                + " \"fss\":\"" + dr[3].ToString() + "\"},";
            }
            sysIdList = sysIdList.Substring(0, sysIdList.Length - 1);//去掉最后的一个逗号
            sysIdList = sysIdList + "]";
            context.Response.Write(sysIdList.ToString());
        }else if (methodName == "savestate"){//判断是否为保存设备状态的方法
            //获取前台ajax传过来的设备状态数据
            string devicestate = context.Request["devicestate"];
            JObject jo = (JObject)JsonConvert.DeserializeObject(devicestate);
            //获得状态名称
            string name = jo["name"].ToString();
            //获得状态值
            string value = jo["value"].ToString();
            //获得当前系统时间（字符串格式）
            string systemTime = DateTime.Now.ToString();
            //插入数据库
            string strSql = "insert into device_state(name,value,createtime)values('" + name + "','" + value + "','" + systemTime + "')";
            YunCutDBHelper.ExecuteSql(strSql);
        }else if (methodName == "querydevicestate"){//查询设备状态信息
            //查询从数据库查询当前设备状态信息
            DataSet ds = YunCutDBHelper.Query("select top 3 name,value from device_state order by id desc");
            //遍历循环DataSet结果集
            string sysIdList = "[";
            foreach (DataRow dr in ds.Tables[0].Rows){
                decimal v = Convert.ToInt32(dr[1]);
                Decimal value = Math.Round(v , 0);
                sysIdList = sysIdList + "{ \"name\":\"" + dr[0].ToString() + "\","
                + " \"value\":\"" + value + "\"},";
            }
            sysIdList = sysIdList.Substring(0, sysIdList.Length - 1);//去掉最后的一个逗号
            sysIdList = sysIdList + "]";
            context.Response.Write(sysIdList.ToString());
        }else if (methodName == "queryonline"){//查询设备状态信息
            //查询从数据库查询当前设备状态信息
            DataSet ds = YunCutDBHelper.Query("select top 1 value from device_state where name='生产' order by id desc");
            //遍历循环DataSet结果集
            string sysIdList = "[";
            foreach (DataRow dr in ds.Tables[0].Rows){
                decimal value = Convert.ToInt32(dr[0]);
                Decimal online = Math.Round((value / 19)*10000 , 0);
                string aims = "10000";
                sysIdList = sysIdList + "{ \"aims\":\"" + aims + "\","
                + " \"actual\":\"" + online + "\"}";
            }
            sysIdList = sysIdList + "]";
            context.Response.Write(sysIdList.ToString());
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}